using System;
using System.Collections.Generic;

namespace ICommonLibrary.Collection {

    public class WeakDictionary<TK, TV> {

        private readonly Dictionary<TK, WeakReference> _dict;

        public WeakDictionary() {
            _dict = new Dictionary<TK, WeakReference>();
        }

        public int Count {
            get {
                return _dict.Count;
            }
        }

        public void Add(TK key, TV value) {
            _dict[key] = new WeakReference(value, false);
        }

        public TV Get(TK key) {
            WeakReference reference;
            if (_dict.TryGetValue(key, out reference)) {
                return (TV)reference.Target;
            }
            return default(TV);
        }

        public void Remove(TK key) {
            _dict.Remove(key);
        }
    }
}